import urllib
from google.appengine.api import urlfetch
from django.conf import settings

API_SSL_SERVER="https://api-secure.recaptcha.net"
API_SERVER="http://api.recaptcha.net"
VERIFY_SERVER="api-verify.recaptcha.net"

class RecaptchaResponse(object):
    def __init__(self, is_valid, error_code=None):
        self.is_valid = is_valid
        self.error_code = error_code
        
def submit(recaptcha_challenge_field, recaptcha_response_field, remoteip):
    """
    Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
    for the request

    recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form
    recaptcha_response_field -- The value of recaptcha_response_field from the form
    remoteip -- the user's ip address

    takes from settings:
    RECAPTCHA_PRIVATE_KEY -- your reCAPTCHA private key
    
    """
    private_key = settings.RECAPTCHA_PRIVATE_KEY
    
    if not (recaptcha_response_field and recaptcha_challenge_field and
            len (recaptcha_response_field) and len (recaptcha_challenge_field)):
        return RecaptchaResponse(
            is_valid= False,
            error_code='incorrect-captcha-sol')
        
    params = urllib.urlencode({
	    'privatekey': private_key,
            'remoteip': remoteip,
	    'challenge': recaptcha_challenge_field,
	    'response': recaptcha_response_field,
	    })

    result = urlfetch.fetch(
        "http://%s/verify" % VERIFY_SERVER,
        params,
        urlfetch.POST
        )
    return_values = result.content.splitlines()
    return_code = return_values[0]
    if (return_code == "true"):
        return RecaptchaResponse(is_valid=True)
    else:
        return RecaptchaResponse(is_valid=False, error_code=return_values[1])
